var countDeafRats = function(town) {
    var left_part = town.slice(0, town.indexOf('P')).replace(/\s/g, '');
    var right_part = town.slice(town.indexOf('P') + 1).replace(/\s/g, '');
    return (left_part.match(/(.{2})/g) || []).filter(v => v === 'O~').length +
        (right_part.match(/(.{2})/g) || []).filter(v => v === '~O').length
}

countDeafRats('~O~O~O~O~O~O  O~~OPO~O~O~O~O~O~O~O~O~O~O~O~O~~OO~O~O~  O~O~')